import socket
from threading import Thread
from csgdecoder import *
from csgencoder import *
from framehandler import *
from usercmd import *

cmd = UserCmd()
# TCP服务器处理客户端连接的函数
def handle_client(client_socket, client_address):
    try:
        while True:
            # 接收数据
            raw_frame = client_socket.recv(1024)  # 假设每个帧最多1024字节
            if not raw_frame:
                break  # 客户端断开连接

            print("rx {}:".format(client_address), raw_frame.hex())

            # 解析帧
            frame_handler = FrameHandler()
            frame_info = frame_handler.parse_frame(raw_frame) 
            if frame_info:
                # 处理帧并构建响应
                rsp_frame = frame_handler.handle_frame(frame_info)
                if rsp_frame:
                    client_socket.sendto(rsp_frame, client_address)
                    print("tx:", rsp_frame.hex())
            else:
                print("Error parsing frame from {}: {}".format(client_address, frame_info))

    except Exception as e:
        print("Error handling client {}: {}".format(client_address, e))
    finally:
        client_socket.close()

# 创建TCP服务器
def start_server(host='0.0.0.0', port=9999):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((host, port))
    server_socket.listen(5)
    print(f"TCP Server started on {host}:{port}. Waiting for connections...")

    try:
        while True:
            client_socket, client_address = server_socket.accept()
            print(f"Accepted connection from {client_address[0]}:{client_address[1]}")
            cmd.set_socket(client_socket)
            client_thread = Thread(target=handle_client, args=(client_socket, client_address))
            client_thread.start()
    except KeyboardInterrupt:
        print("Shutting down the server...")
        server_socket.close()

def test_():
    # 您提供的帧字节串
    raw_frame = bytes.fromhex('681900190068c91111000100000002700000001000e01101015832091704243316')
    print(raw_frame.hex())
    # 解析帧
    frame_info = parse_frame(raw_frame)
    
    print(frame_info) 
    frame_info["User Data Info"]["AFN"] = '00'
    frame_info["User Data Info"]["DI"] = '00000000'
    frame_info["User Data Info"]["Data"] = '00'
    f = build_frame(frame_info)
    print(f.hex())

if __name__ == "__main__":
    cmd.listen_for_input()
    start_server()

